<template>
  <div>
    <chooseTable
      ref="spareTable"
      :type="type"
      :isShowPage="false"
      :instiutionTableData="spareTableData"
      :instiutionTableHeader="spareTableHeader"
    >
      <template #spareNumber="{ scope }">
          {{ allCommodityCodeObj[scope.row.id].spareNumber }}
        </template>
    </chooseTable>
    <div id="showPopBtn" @click="handleWareHouse">
      <i class="el-icon-plus" />添加备件
    </div>
    <div
      v-if="stockShow"
      ref="stockPop"
      class="popList"
      :style="searchShow ? '' : popStyle"
    >
      <el-input
        v-if="searchShow"
        v-model="search"
        placeholder="搜索字段"
        prefix-icon="el-icon-search"
        @input="handleSearchChange"
      />
      <el-table :data="sparePopList" @row-click="chooseRow" max-height="240px">
        <el-table-column label="备件名称" prop="name" />
        <el-table-column
          label="类型"
          :width="60"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.typeId | filterTypeName }}
          </template>
        </el-table-column>
        <el-table-column label="型号" prop="model" />
      </el-table>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Mixins } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import chooseTable from './chooseTable.vue'
import { deepClone, commonAction } from '@/utils/common'
import { state } from '../store/spareData'
import filterTypeName from '../mixins/filterTypeName'
@Component({
  name: 'chooseSpareParts',
  components: {
    QuickSearch,
    chooseTable
  }
})
export default class ChooseSpare extends Mixins(filterTypeName) {
  @Prop() private spareTableData!: any // 表格数据

  @Prop() private type!: number // 区分入库、出库

  private $confirm: any

  private $message: any

  private sparePopList: any = [] // 备件弹窗表格数据

  private searchArr: any = [] // 弹框搜索出来的数据

  private stockShow: boolean = false // 备件弹窗开关

  private positionRow: any = 0 // 点击表格的多少行

  private search: any = '' // 弹窗搜索字段

  private searchShow: boolean = true // 弹框搜索栏

  private inputEl: any = '' // 获取焦点的dom

  private rowNum: number = 0 // 点击的表格行数

  private focusRow: any = {} // 获取焦点的表格数据

  private popListCopy: any = [] // 弹窗表格数据备份

  private spareTableHeader: any[] = [ // 表头
    { label: '备件编号', prop: 'spareNumber', custom: true },
    { label: '备件名称', prop: 'name', type: 'input', width: 100, handleClick: (event: any, row: any) => this.handleClick(event, row), handleFocus: (row: any) => this.handleChange(row), handleBlur: (row: any) => this.handleBlur(row) },
    { label: '类型', prop: 'typeIdName', width: 100 },
    { label: '型号', prop: 'model' },
    { label: '当前库存', prop: 'stockNum' },
    { inLabel: '入库数量', outLabel: '出库数量', prop: 'number', type: 'inputNumber', limitNum: 'stockNum', width: '100px', handleNumChange: (val: any, row: any) => this.handleNumChange(val, row) },
    {
      label: '操作',
      width: 60,
      handlers: [
        { className: 'danger', name: '删除', handleFn: (scope: any) => this.handleDel(scope.row) }
      ]
    }
  ]

  get popStyle () { // 输入框获取焦点弹框显示的位置
    const { spareTableData, rowNum } = this
    return {
      top: -((spareTableData.length - rowNum) * 40 + 44) + 'px'
    }
  }

  public clearPopData () {
    this.popListCopy = []
    this.sparePopList = []
  }

  private get allCommodityCodeObj () { // 备件类型
    return state.allCommodityCodeObj
  }

  private handleNumChange (val, row) {
    if (String(val).indexOf('.') > -1) {
      row.number = String(val).split('.')[0]
      this.$message.error('只能输入正整数')
    }
  }

  private handleSearchChange (val: any) { // 搜索联想数据
    if (val) {
      this.searchArr = []
      this.popListCopy.forEach(item => {
        if (item.name.indexOf(val) > -1) {
          this.searchArr.push(item)
        }
      })
      this.sparePopList = deepClone(this.searchArr)
    } else {
      this.sparePopList = deepClone(this.popListCopy)
    }
  }

  private handleClick (event: any, row: any) {
    this.rowNum = row.index + 1 // 点击的表格行数,超过5行显示
    this.inputEl = event && event.target
    this.focusRow = deepClone(row)
    this.stockShow = true
    this.searchShow = false
    this.handleSearchChange(row.name)
  }

  private handleChange (val: any) {
    this.handleSearchChange(val.name)
  }

  private handleBlur (row: any) {
    if (!row.name || !this.searchArr.length) {
      row.name = this.focusRow.name
    }
  }

  private getSpareName (id: any, type: number) { // 获取备件类型名字 1类型 2备件名称
    if (type === 1) {
      if (!id) {
        return ''
      }
      const ids = id.split(',')
      let result = ''
      ids.forEach(item => {
        result += state.allSpareTypeObj[item]?.typeName + '/'
      })
      return result.slice(0, result.length - 1)
      // const spareType = state.allSpareTypeObj[id]
      // return spareType && spareType.typeName
    } else if (type === 2) {
      const spare = state.allCommodityCodeObj[id]
      return spare && spare.name
    }
    return ''
  }

  public getSparePopData (id: any) { // 获取备件弹窗表格数据
    const actionData = {
      url: this.type === 1 ? '/server-work/action/spare/queryInStock' : '/server-work/action/spare/queryOutStock',
      method: 'post',
      data: { wareHouseId: id }
    }
    commonAction(actionData).then(res => {
      if (res.success) {
        res.data.list.forEach(item => {
          item.typeIdName = this.getSpareName(item.typeId, 1)
          item.name = this.getSpareName(item.id, 2)
        })
        this.sparePopList = res.data.list
        console.log(this.sparePopList, state.allCommodityCodeObj, 77888)
        this.popListCopy = deepClone(this.sparePopList) // 数据备份
        this.$emit('clearDataList') // 更换仓库 清空已选中的备件列表
      }
    })
  }

  private handleDel (row: any) { // 删除表格中的备件
    (this.$confirm as any)('确定删除该备件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.sparePopList.push(row) // 删除的数据添加到备件弹窗中
      this.popListCopy.push(row) // 删除的数据添加到备件弹窗中
      const index = this.spareTableData.findIndex(item => item.id === row.id)
      this.spareTableData.splice(index, 1) // 表格数据移除删除的数据
    })
  }

  private handleWareHouse () { // 显示弹窗
    this.$emit('checkHouse')
    this.sparePopList = deepClone(this.popListCopy)
    this.stockShow = true
    this.searchShow = true
  }

  private chooseRow (row) { // 弹窗选中事件
    if (!this.searchShow) {
      this.spareTableData.push(row) // 选中的数据添加到表格中

      const index = this.popListCopy.findIndex(item => item.id === row.id)
      this.sparePopList.splice(index, 1) // 弹框中移除数据
      this.popListCopy.splice(index, 1)

      this.sparePopList.push(this.focusRow) // 弹框中添加表格替换掉的数据
      this.popListCopy.push(this.focusRow)

      const idx = this.spareTableData.findIndex(item => item.id === row.id)
      this.spareTableData.splice(idx, 1) // 表格中移除替换掉的数据

      this.stockShow = false
      return
    }
    (this as any).spareTableData.push(row) // 选中的数据添加到表格中
    const ind = this.popListCopy.findIndex(item => item.id === row.id)
    this.sparePopList.splice(ind, 1) // 备件弹窗移除选中的备件
    this.popListCopy.splice(ind, 1) // 备份弹窗移除选中的备件
  }

  private closesStockPop (e: any) { // 点击非弹窗区域取消弹窗
    const ref: any = this.$refs.stockPop
    const btnDom: any = document.getElementById('showPopBtn')
    if (this.inputEl ? ref && !ref.contains(e.target) && btnDom && !btnDom.contains(e.target) && !this.inputEl.contains(e.target) : ref && !ref.contains(e.target) && btnDom && !btnDom.contains(e.target)) {
      this.stockShow = false
    }
  }

  private mounted () { // 监听非弹窗区域得点击事件
    document.addEventListener('click', this.closesStockPop)
  }

  private beforeDestroy () { // 移除非弹窗区域点击事件的监听
    document.removeEventListener('click', this.closesStockPop)
  }
}
</script>

<style lang="stylus" scoped>
#showPopBtn
  width 100px
  color #008BEE
  font-size 12px
  font-family PingFang SC
  line-height 44px
  cursor pointer
  .el-icon-plus
    margin-right 6px
.popList
  width 360px
  max-height 300px
  background #FFFFFF
  box-shadow 0px 4px 29px 0px rgba(155,165,172,0.46)
  border-radius 4px
  padding 10px 12px
  position relative
  top -44px
.el-input
  margin-bottom 10px
.el-table
  font-size 12px
  font-family PingFang SC
  color #303753
  >>> .el-table__header th
    padding 0
    height 34px
  >>> .el-table__body td
    padding 0
    height 34px
</style>
